package com.ning.activitys.skysound.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ning.activitys.skysound.R;
import com.ning.activitys.skysound.adpter.MainAdapter;
import com.ning.activitys.skysound.base.BaseActivity;
import com.ning.activitys.skysound.base.MyApplication;
import com.ning.activitys.skysound.beans.GsonRadioDetails;
import com.ning.activitys.skysound.beans.MusicDetailsBeans;
import com.ning.activitys.skysound.beans.SongBeans;
import com.ning.activitys.skysound.datas.MusicDetailsTool;
import com.ning.activitys.skysound.fragment.mymusic.AllMusicFragment;
import com.ning.activitys.skysound.fragment.mymusic.LikeMusicFragment;
import com.ning.activitys.skysound.service.PlayService;

import java.util.ArrayList;

import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;


public class MainActivity extends BaseActivity implements View.OnClickListener {

    private ViewPager viewPager;
    private MainAdapter mainAdapter;
    private TabLayout tabLayout;

    private ImageView singerImage;
    private TextView songName,singerName;
    private ImageView lastSong,playSong,nextSong;
    private RelativeLayout relativeLayout;
    private ImageButton search;
    private SongBeans netSongBeans;

    private ArrayList<MusicDetailsBeans> musicDetailsData = new ArrayList<>();

    private int position = 0;//当前播放的是第几首歌

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);


        setContentView(R.layout.activity_main);

        viewPager = (ViewPager) findViewById(R.id.view_pager_main_activity);
        tabLayout = (TabLayout) findViewById(R.id.tab_layout_main);

        singerImage = (ImageView) findViewById(R.id.iv_singer_image_main);
        songName = (TextView) findViewById(R.id.tv_song_name_main);
        singerName = (TextView) findViewById(R.id.tv_singer_name_main);
        playSong = (ImageView) findViewById(R.id.iv_song_play_main);
        nextSong = (ImageView) findViewById(R.id.iv_song_next_main);
        lastSong = (ImageView) findViewById(R.id.iv_song_last_main);
        relativeLayout = (RelativeLayout) findViewById(R.id.rl_relative_layout_main);
        search = (ImageButton) findViewById(R.id.btn_main_activity_search);


        playSong.setOnClickListener(this);
        lastSong.setOnClickListener(this);
        nextSong.setOnClickListener(this);
        relativeLayout.setOnClickListener(this);
        search.setOnClickListener(this);

        findViewById(R.id.btn_main_activity_set).setOnClickListener(this);


        mainAdapter = new MainAdapter(getSupportFragmentManager());
        viewPager.setAdapter(mainAdapter);
        tabLayout.setupWithViewPager(viewPager);
        tabLayout.setSelectedTabIndicatorColor(0);
        tabLayout.setTabTextColors(Color.WHITE, Color.BLACK);

    }



    @Override
    protected void onResume() {
        super.onResume();
        bindPlayService();
    }

    @Override
    protected void onPause() {
        super.onPause();
        unBindPlayService();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        /**
         * 保存一些下次启动需要用的数据
         * */
        MyApplication myApplication = (MyApplication) getApplication();
        SharedPreferences.Editor editor  = myApplication.sharedPreferences.edit();
        editor.putInt("currentPlayPosition",playService.getCurrentPlayPosition());
        editor.putInt("play_mode", playService.getPlay_mode());
        editor.commit();



    }

    //更新播放状态的抽象方法
    @Override
    public void publish(int progress) {
        //更新进度条

    }
    @Override
    public void change(int position) {

        if (PlayService.IS_NET_MUSIC == 1) {

            //切换状,态播放位置
            if (viewPager.getCurrentItem() == 0) {

                changeUIStatusOnPlay(playService.getCurrentPlayPosition());

            } else if (viewPager.getCurrentItem() == 1) {

                changeUIStatusOnPlay(playService.getCurrentPlayPosition());
            }
        }else if (PlayService.IS_NET_MUSIC == 0){

            netChangeUIStatusOnPlay();

        }

    }



    /**
     * 本类的监听事件
     *
     * */
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_main_activity_set:
                Intent intent = new Intent(MainActivity.this,SetActivity.class);
                startActivity(intent);
                break;

            case R.id.iv_song_play_main:
                if (playService.isPlay()){
                    playSong.setImageResource(R.mipmap.bofanganniuone);
                    playService.pause();

                }else {
                    playSong.setImageResource(R.mipmap.zantinganniusix);
                    if (playService.isPause()){
                        playService.start();
                    }else {
                        playService.play(playService.getCurrentPlayPosition());
                    }

                }
                break;
            case R.id.iv_song_next_main:
                playService.next();
                break;
            case R.id.iv_song_last_main:
                playService.last();
                break;
            case R.id.rl_relative_layout_main:
                Intent intentToPlay = new Intent(this, PlayActivity.class);

                startActivity(intentToPlay);


                break;

            case R.id.btn_main_activity_search:
                showShare();
                break;

            default:
                break;
        }
    }

    //播放状态下的UI 设置
    public void changeUIStatusOnPlay(int position){

        musicDetailsData = (ArrayList)playService.getMusicDetailsData();

        if (position >= 0 && position <  musicDetailsData.size()){

            MusicDetailsBeans musicDetailsBeans = musicDetailsData.get(position);
            songName.setText(musicDetailsBeans.getTitle());
            singerName.setText(musicDetailsBeans.getArtist());

            Bitmap albumBitmap = MusicDetailsTool.getArtwork(this,
                    musicDetailsBeans.getId(), musicDetailsBeans.getAlbumID(),
                    true, true);
            singerImage.setImageBitmap(albumBitmap);

            if (playService.isPlay()) {
                playSong.setImageResource(R.mipmap.zantinganniusix);
            }else {
                playSong.setImageResource(R.mipmap.bofanganniuone);
            }

            //存储当前播放第几首
            this.position = position;
        }
    }


    public void netChangeUIStatusOnPlay(){

         this.netSongBeans = playService.getNetSongBeans();

        if (null != this.netSongBeans) {

            songName.setText(this.netSongBeans.getTitle());
            singerName.setText(this.netSongBeans.getSingerName());
        }

        if (playService.isPlay()) {
            playSong.setImageResource(R.mipmap.zantinganniusix);
        }else {
            playSong.setImageResource(R.mipmap.bofanganniuone);
        }
    }



    private void showShare() {
        ShareSDK.initSDK(this);
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();

// 分享时Notification的图标和文字  2.5.9以后的版本不调用此方法
        //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
        oks.setTitle("uuu");
        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
        oks.setTitleUrl("http://sharesdk.cn");
        // text是分享文本，所有平台都需要这个字段
        oks.setText("我是分享文本");
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        //oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl("http://sharesdk.cn");
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oks.setComment("我是测试评论文本");
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite(getString(R.string.app_name));
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl("http://sharesdk.cn");

// 启动分享GUI
        oks.show(this);
    }
}


/**
 * 多态的定义：指允许不同类的对象对同一消息做出响应。即同一消息可以根据发送对象的不同而采用多种不同的行为方式。（发送消息就是函数调用）
 实现多态的技术称为：动态绑定（dynamic binding），是指在执行期间判断所引用对象的实际类型，根据其实际的类型调用其相应的方法。
 多态的作用：消除类型之间的耦合关系。
 现实中，关于多态的例子不胜枚举。比方说按下 F1 键这个动作，如果当前在 Flash 界面下弹出的就是 AS 3 的帮助文档；
 如果当前在 Word 下弹出的就是 Word 帮助；在 Windows 下弹出的就是 Windows 帮助和支持。同一个事件发生在不同的对象上会产生不同的结果。
 再简单一点：坐公车时，一个男的靠在你的肩膀，你可能不爽，但是如果一个美女靠在你的肩膀你就很乐意，这就是多态的表现
 * */